package com.haoran.dwz.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.haoran.dwz.domain.entities.Personalization;
import com.haoran.dwz.domain.entities.PersonalizationSetting;
import com.haoran.dwz.domain.entities.UserPersonalizationPK;
import com.haoran.dwz.repository.PersonalizationRepository;
import com.haoran.dwz.repository.PersonalizationSettingRepository;
import com.haoran.dwz.service.PersonalizationService;

@Service
public class PersonalizationServiceImpl implements PersonalizationService {

	@Autowired
	private PersonalizationSettingRepository personalizationSettingRepository;

	@Autowired
	private PersonalizationRepository personalizationRepository;

	@Override
	public void setPersonalization(String userId, String number, String value) {
		PersonalizationSetting entities = new PersonalizationSetting();
		entities.setUserId(userId);
		Personalization personalization = personalizationRepository.findByNumber(number);
		if (personalization == null) {
			init();
		}
		personalization = personalizationRepository.findByNumber(number);
		String personalizationId = personalization.getId();
		entities.setPersonalizationId(personalizationId);
		entities.setValue(value);
		personalizationSettingRepository.save(entities);
	}

	private void init() {
		Personalization p1 = new Personalization();
		p1.setNumber("theme");
		p1.setDescription("主题");
		personalizationRepository.save(p1);
		Personalization p = new Personalization();
		p.setNumber("head");
		p.setDescription("头像");
		personalizationRepository.save(p);
	}

	@Override
	public String getPersonalization(String userId, String number) {
		UserPersonalizationPK id = new UserPersonalizationPK();
		id.setUserId(userId);
		Personalization personalization = personalizationRepository.findByNumber(number);
		if (personalization == null) {
			init();
			return null;
		}
		String personalizationId = personalization.getId();
		id.setPersonalizationId(personalizationId);
		if(personalizationSettingRepository.exists(id)) {
			PersonalizationSetting one = personalizationSettingRepository.getOne(id);
			return one.getValue();
		}
		return null;
	}
}
